<template>
  <div>
    <el-dialog
      v-model="state.show"
      :title="hasAccount ? '编辑发票' : '新增开票'"
      width="700px"
      modal-class="unReconciled-dailog"
      @close="handleClose"
    >
      <el-form
        label-suffix="："
        ref="InvoiceForm"
        :model="state.modfiyForm"
        :rules="state.invoiceRules"
        label-width="100px"
        size="small"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="单据流水号">
              <el-input
                v-model="state.modfiyForm.doccode"
                placeholder="请输入"
                style="width: 100%"
                :disabled="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="开票类型"
              label-width="100px"
              prop="invoiceTypeId"
            >
              <el-select
                v-model="state.modfiyForm.invoiceTypeId"
                placeholder="请选择开票类型"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="item in state.InvoiceList"
                  :key="item.invoicetypeCode"
                  :label="item.invoicetypeName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="开票对象"
              label-width="100px"
              prop="invoiceObjId"
            >
              <el-select
                v-model="state.modfiyForm.invoiceObjId"
                placeholder="请选择开票对象"
                style="width: 100%"
                clearable
                filterable
                remote
                :remote-method="getBusDetail"
                @change="changeEntName"
                @blur="formValidateField('InvoiceObjId')"
                :loading="state.settlementLoading"
              >
                <el-option
                  v-for="item in state.settlementList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="一般纳税人">
              <el-input
                v-model="state.modfiyForm.generalTaxpayer"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="币别" prop="currencyCode">
              <el-select
                v-model="state.modfiyForm.currencyCode"
                placeholder="请选择币别"
                style="width: 100%"
                clearable
                filterable
                remote
                :remote-method="getCurrentData"
                :loading="state.currentLoading"
                @blur="formValidateField('currencyCode')"
                @change="currencyChange"
                :disabled="hasAccount"
              >
                <el-option
                  v-for="item in state.current"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <span style="float: left"> {{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行名称" prop="bankName">
              <el-input
                v-model="state.modfiyForm.bankName"
                placeholder="请输入银行名称"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话">
              <el-input
                v-model="state.modfiyForm.telephone"
                placeholder="请输入电话"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input
                v-model="state.modfiyForm.bankAccount"
                placeholder="请输入银行账号"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="纳税人识别号" prop="taxpayerNumber">
              <el-input
                v-model="state.modfiyForm.taxpayerNumber"
                placeholder="请输入纳税人识别号"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发票抬头" prop="invoiceTitle">
              <el-input
                v-model="state.modfiyForm.invoiceTitle"
                placeholder="请输入发票抬头"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="地址">
              <el-input
                v-model="state.modfiyForm.address"
                placeholder="请输入地址"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div>
          <el-button type="default" @click="state.show = false">取消</el-button>
          <el-button type="primary" @click="modifySubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  onMounted,
  defineProps,
  defineEmits,
  nextTick
} from 'vue'
import request from '@/public/request'
import { ElMessage } from 'element-plus'

const props = defineProps({
  // 是否已对账
  hasAccount: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['getList'])

const state = reactive({
  show: false,
  // 发票修改信息
  modfiyForm: {
    doccode: '', //开票单号
    invoiceObjId: '', //开票对象ID
    invoiceTypeId: '', //发票类型对象ID
    generalTaxpayer: '', // 一般纳税人
    currencyCode: '', //币种代码
    currencyName: '', //币种名称
    bankName: '', //银行名称
    bankAccount: '', //银行账号
    feeIdArray: [], //费用Ids
    telephone: '', //电话
    taxpayerNumber: '', //纳税人识别号
    invoiceTitle: '', //发票抬头
    address: '' //地址
  },
  invoiceRules: {
    currencyCode: [{ required: true, message: '请选择币别', trigger: 'blur' }],
    bankName: [{ required: true, message: '请输入银行名称', trigger: 'blur' }],
    bankAccount: [
      { required: true, message: '请输入银行账号', trigger: 'blur' }
    ],
    taxpayerNumber: [
      { required: true, message: '请输入纳税人识别号', trigger: 'blur' }
    ],
    invoiceTitle: [
      { required: true, message: '请输入发票抬头', trigger: 'blur' }
    ],
    invoiceObjId: [
      { required: true, message: '请选择开票对象', trigger: 'blur' }
    ],
    invoiceTypeId: [
      { required: true, message: '请选择开票类型', trigger: 'change' }
    ]
  },
  settlementList: [],
  settlementLoading: false,
  current: [],
  currentLoading: false,
  InvoiceList: []
})

const InvoiceForm = ref()

const formValidateField = (key) => {
  InvoiceForm.value.validateField(key)
}
const currencyChange = (val) => {
  if (!val) {
    state.modfiyForm.currencyName = ''
    InvoiceForm.value.validateField('currencyCode')
    return
  }
  let arr = state.current.filter((i) => {
    return i.value == val
  })
  state.modfiyForm.currencyName = arr[0].label.split('|')[1]
  InvoiceForm.value.validateField('currencyCode')
}

// 获取结算对象的数据
const getBusDetail = async (val) => {
  state.settlementLoading = true
  let res = await request.get('/api/buenterprise/dropdownlist', {
    KeyWords: val
  })
  res.forEach((item) => {
    item.label = item.entFullname
    item.value = item.id
  })
  state.settlementList = res
  state.settlementLoading = false
}
// 重置数据
const resetModfiyForm = () => {
  state.modfiyForm = {
    doccode: '', //开票单号
    invoiceObjId: '', //开票对象ID
    invoiceTypeId: '', //发票类型对象ID
    generalTaxpayer: '', // 一般纳税人
    currencyCode: '', //币种代码
    currencyName: '', //币种名称
    bankName: '', //银行名称
    bankAccount: '', //银行账号
    feeIdArray: [], //费用Ids
    telephone: '', //电话
    taxpayerNumber: '', //纳税人识别号
    invoiceTitle: '', //发票抬头
    address: '' //地址
  }
}

// 关闭弹框
function handleClose() {
  if (!props.hasAccount) {
    InvoiceForm.value.resetFields()
  }
}

// 打开弹窗
const openDialog = async (row) => {
  resetModfiyForm()
  let api = ''
  if (!props.hasAccount) {
    // add
    api = '/api/bucode/doccodeSerialByCode'
    const entId = [row[0].entId]
    const feeIds = []
    row.forEach((item) => {
      feeIds.push(item.id)
      if (!entId.some((val) => item.entId === val)) {
        entId.push(item.entId)
      }
    })
    if (entId.length == 1) {
      state.modfiyForm.invoiceObjId = entId[0]
      state.settlementList = [
        {
          label: row[0].entFullname,
          value: entId[0]
        }
      ]
    }
    state.modfiyForm.feeIdArray = feeIds
    let res = await request.get(api, {
      code: 'SYS_INVOICE'
    })
    state.modfiyForm.doccode = res ? res : ''
    // state.modfiyForm.invoiceTypeId = state.InvoiceList.legnth != 0 ? state.InvoiceList[0].id : null;
  } else {
    console.log(row)
    // edit
    if (row.invoiceObjId) {
      let res = await request.get('/api/buenterprise/dropdownlist', {
        id: row.invoiceObjId
      })
      res.forEach((item) => {
        item.label = item.entFullname
        item.value = item.id
      })
      state.settlementList = res
      console.log(row.currencyCode)
      state.modfiyForm = {
        doccode: row.doccode, //开票单号
        invoiceObjId: row.invoiceObjId, //开票对象ID
        invoiceTypeId: row.invoiceTypeId, //发票类型对象ID
        generalTaxpayer: row.generalTaxpayer, // 一般纳税人
        currencyCode: row.currencyCode, //币种代码
        currencyName: '', //币种名称
        bankName: row.bankName, //银行名称
        bankAccount: row.bankAccount, //银行账号
        feeIdArray: [], //费用Ids
        telephone: row.telephone, //电话
        taxpayerNumber: row.taxpayerNumber, //纳税人识别号
        invoiceTitle: row.invoiceTitle, //发票抬头
        address: row.address, //地址
        id: row.id
      }
    }
  }
  state.show = true
}

const changeEntName = (val) => {}

// 开票提交
const modifySubmit = async () => {
  let valid = await InvoiceForm.value.validate()
  if (valid) {
    let api = ''
    if (!props.hasAccount) {
      api = '/api/invoice/create'
      delete state.modfiyForm.id
    } else {
      api = '/api/invoice/update'
      delete state.modfiyForm.feeIdArray
    }
    let res = await request.post(api, state.modfiyForm)
    if (res.status) {
      // ctx.emit('getList')
      emit('getList')
      ElMessage.success('成功')
      state.show = false
    } else {
      ElMessage.warning(res.message)
    }
  }
}

// 获取币种类型
const getCurrentData = async (val) => {
  state.currentLoading = true
  let res = await request.get('/api/base/currency/dropdownlist', {
    keywords: val
  })
  state.current = res.map((item) => {
    return {
      label: item.currencyCode + '|' + item.currencyName,
      value: item.currencyCode
    }
  })
  state.currentLoading = false
}
// 获取发票类型
const getInvoiceList = async () => {
  let res = await request.get('/api/base/invoice/queryList')
  state.InvoiceList = res
}

defineExpose({
  openDialog
})

onMounted(() => {
  getInvoiceList()
  getCurrentData()
})
</script>

<style scoped></style>
<style lang="scss">
.unReconciled-dailog {
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
  }

  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;

    div {
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }
}
</style>
